<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleAdd" v-if="hasPermission('messages:blog_messages:add')">
          <Icon icon="ant-design:plus-outlined" /> 新增
        </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '编辑',
                onClick: handleEdit.bind(null, record),
                auth: 'messages:blog_messages:edit',
              },
              {
                label: '删除',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
                auth: 'messages:blog_messages:delete',
              },
            ]"
            :dropDownActions="[
              {
                label: '审核通过',
                onClick: handleApprove.bind(null, record),
                auth: 'messages:blog_messages:edit',
                ifShow: record.status === 0,
              },
              {
                label: '拒绝',
                onClick: handleReject.bind(null, record),
                auth: 'messages:blog_messages:edit',
                ifShow: record.status === 0,
              },
            ]"
          />
        </template>
        <template v-else-if="column.key === 'status'">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusText(record.status) }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'content'">
          <div class="content-cell">
            <span>{{ record.content }}</span>
          </div>
        </template>
      </template>
    </BasicTable>
    <BlogMessagesModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';

  import BlogMessagesModal from './BlogMessagesModal.vue';
  import { columns, searchFormSchema } from './message.data';
  import { deleteOne, duplicate, getImportUrl, getExportUrl, getList, updateOne, deleteBatch } from './message.api';
  import { downloadByUrl } from '/@/utils/file/download';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { useMessage } from '/@/hooks/web/useMessage';

  defineOptions({ name: 'BlogMessagesList' });

  const checkedKeys = ref<Array<string | number>>([]);
  const { hasPermission } = usePermission();
  const { createMessage } = useMessage();

  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = useTable({
    title: '留言管理',
    api: getList,
    rowKey: 'id',
    columns: columns,
    canResize: false,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
    },
    showTableSetting: true,
    bordered: true,
    showIndexColumn: false,
    canColDrag: true,
    actionColumn: {
      width: 120,
      fixed: 'right',
      label: '操作',
      key: 'action',
    },
    beforeFetch: (params) => {
      return Object.assign(params);
    },
  });

  function handleAdd() {
    openModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }

  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }

  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }

  async function handleApprove(record) {
    // 审核通过
    await updateStatus(record.id, 1);
  }

  async function handleReject(record) {
    // 拒绝
    await updateStatus(record.id, 2);
  }

  async function updateStatus(id: string, status: number) {
    try {
      await updateOne({ id, status });
      createMessage.success('操作成功');
      reload();
    } catch (error) {
      createMessage.error('操作失败');
    }
  }

  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }

  function handleDuplicate(record: Recordable) {
    duplicate({ id: record.id }, handleSuccess);
  }

  async function handleBatchDelete() {
    await deleteBatch({ ids: selectedRowKeys.value }, handleSuccess);
  }

  function handleImportExcel() {
    getImportUrl((url) => {
      downloadByUrl({ url });
    });
  }

  function handleExport() {
    getExportUrl(null, (url) => {
      downloadByUrl({ url });
    });
  }

  function getStatusColor(status: number) {
    switch (status) {
      case 0:
        return 'orange';
      case 1:
        return 'green';
      case 2:
        return 'red';
      default:
        return 'default';
    }
  }

  function getStatusText(status: number) {
    switch (status) {
      case 0:
        return '待审核';
      case 1:
        return '已发布';
      case 2:
        return '已拒绝';
      default:
        return '未知';
    }
  }
</script>

<style scoped>
  .content-cell {
    max-width: 300px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style> 